/**
 * 
 */
$(function(){
    $(document).keyup(function (e) {
        if(e.which==13){
            $('#selectBtnEnter').click();
        }
    })
});
var path = '../';
var pageListUrl = path + 'advInfo/list';
var pageUrl = path + 'advInfo/';

//添加弹窗
var addPanel = null;
// ---------------交互代码begin-----------------
//本页面业务逻辑
var advInfo={
	checkLogic:function(dataObj,err,fg){
        advInfo.clear(err);
		console.log(dataObj)
		var result="";
		var isSubmit=true;
		//TODO 逻辑校验，去掉不必要的:
		// var reg = /^\w{1,16}$/;
		// if(!reg.test(dataObj.advCode)){
         //    err.advCodeErr="广告编号必须是1-16位字母/数字/下划线组成";
         //    isSubmit=false;
		// }

		result=customUtils.checkLen(dataObj.advName,1,32,'广告名称');
		if(result.length!=0){
            err.advNameErr=result;
			isSubmit=false;
		}

        // var reg = /^\d{1,5}(\.\d{1,2})?$/
        // if (!reg.test(dataObj.price)) {
        //     err.priceErr= "整数位不能超过5位,小数点不能超过2位";
        //     isSubmit=false;
        // }




        var topImg = $("#topImg")[0].files[0];
        var middleVideo = $("#middleVideo")[0].files[0];
        //文件空校验
        if(fg == 'save' && dataObj.advType==6){
            if(!middleVideo){
                err.middleVideoErr = "请上传背景音乐";
                isSubmit = false;
            }
        }else{
            if(fg == 'save'){
                if(!topImg){
                    err.topImgErr = "请上传广告资源";
                    isSubmit = false;
                }
            }
        }

        //文件格式校验
        var imgType = ["jpg","png","gif","jpeg","bmp"];
        var videoType = ["mp4","avi","mov","asf","wmv","rm"];
        var musicType = ["mp3"];
        var videoArray = ["3","8"];
        // if(topImg && bottomImg && middleVideo){
        if(topImg){
            if(dataObj.advType==2){
                return isSubmit;
            }
            var type = topImg.name.substr(topImg.name.lastIndexOf(".") + 1,topImg.name.length).toLowerCase();
            if(videoArray.indexOf(dataObj.advType) == '-1' && $.inArray(type,imgType) == '-1'){
                err.topImgErr = "请上传" + imgType.toString() + "格式的图片";
                isSubmit = false;
            }
            /*if(dataObj.advType!= 3 && $.inArray(type,imgType) == '-1'){
                err.topImgErr = "请上传" + imgType.toString() + "格式的图片";
                isSubmit = false;
            }*/
            /*if(dataObj.advType== 3 && $.inArray(type,videoType) == '-1'){
                err.topImgErr = "请上传" + videoType.toString() + "格式的视频";
                isSubmit = false;
            }*/
            if(videoArray.indexOf(dataObj.advType) != '-1' && $.inArray(type,videoType) == '-1'){
                err.topImgErr = "请上传" + videoType.toString() + "格式的视频";
                isSubmit = false;
            }
            if(videoArray.indexOf(dataObj.advType) == '-1' && topImg.size>5242880){
                err.topImgErr = "上传图片不得大于5M";
                isSubmit = false;
            }
            if(videoArray.indexOf(dataObj.advType) != '-1' && topImg.size>5242880){
                err.topImgErr = "上传视频不得大于5M";
                isSubmit = false;
            }
            if(videoArray.indexOf(dataObj.advType) != '-1' && topImg.size>5242880){
                err.topImgErr = "上传视频不得大于5M";
                isSubmit = false;
            }
        }
        if(middleVideo && dataObj.advType ==6){
            var type = middleVideo.name.substr(middleVideo.name.lastIndexOf(".") + 1,middleVideo.name.length).toLowerCase();
            if($.inArray(type,musicType) == '-1'){
                err.middleVideoErr = "请上传" + musicType.toString() + "格式的音乐";
                isSubmit = false;
            }
            if(middleVideo.size>5242880){
                err.middleVideoErr = "上传素材不得大于5M";
                isSubmit = false;
            }
        }

		console.log(err)
	    //检查表单是否存在错误
		$.each(err, function(key) {
			if(key.indexOf('Err')!=-1 && err[key].length>0){
				return false;
			}									 
		});
		return isSubmit;
	},
	clear:function(obj){
		$.each(obj,function (key) {
			if($.isArray(obj[key])){
				obj[key] = [];
			}else{
				obj[key] = "";
			}
        });
	},
    setCitys:function () {
        addOrUpdate.$data.city = "";
        addOrUpdate.$data.area = "";

    },
    setAreas:function () {
        addOrUpdate.$data.area = "";

    }
};

//绑定列表List---begin----所有的操作都围绕列表展开，新增、更新其他比较独立 
var dataList=new Vue({
	el:"#advInfoList",
	data:{
		pageInfo : {},
		//TODO 自定义条件查询---begin--------			
		condition:{
			page:1,
			rows:customUtils.pageSize,
		    id:"",
		    advCode:"",
		    advName:"",
		    advType:"",
		    maxAge:"",
		    minAge:"",
		    sex:"",
		    advPath:"",
		    areas:"",
		    createdBy:"",
		    createdDate:"",
		    updatedBy:"",
		    updatedDate:"",
		    status:"",
            cameFrom:"",
            advType:"",
			key:""
		},
		//自定义条件查询---end--------
		selectIds:[],//多选
		showSuccess:false,//false不显示成功提示
		selectedIdx:-1,//保存操作行的索引
		isSearch:false,//init:页面初始化；search:点击查询；paging:点击翻页；changePageSize:改变页面显示条数
		selectedPageSize:customUtils.pageSize//修改页面数据显示条数
	},
	mounted: function () {
		//初始化页面数据
		this.getList('init');
        this.getAreaData();
	},
	// 在 `methods` 对象中定义方法,如果操作中函数的逻辑比较复杂，必须封装到dictType对象
	methods:{
	    selectChkBtn:function(e){//用于多选事件
            this.selectIds.push($(e.target).val());
        },
        getAreaData:function () {
            this.$http.get("../appInfo/queryAreaTree").then(function(response){
                console.log(response.body);
                addOrUpdate.$data.provinces = response.body;
                console.log(addOrUpdate.$data)
            },function (res) {
                customUtils.showRequestTips(res,2000)
            });
        },
        openVideo:function (src) {
            var page = window.open();
            var html = "<body style='background:black'>" +
                "<div style='width:80%;margin:auto;'>" +
                "<video controls width='100%' autoplay src='" + src +
                "'></video>" +
                "</div></body>"
            page.document.write(html);
        },
		//搜索、分页列表
		getList:function(eventSrc){				
			var self=this;
			//改变页面显示条数
			if(eventSrc=="changePageSize"){
				if(this.pageInfo.pageSize != this.selectedPageSize){
					this.pageInfo.pageSize=this.selectedPageSize;
					$('#pagination').jqPaginator('destroy');
					eventSrc='init';//重新绘制控件
				}else{
					return;
				}
			}				
			//初始化时无当前页数，后台有默认第1页，每页10条
			if(this.pageInfo!=undefined && this.pageInfo.pageNum!=undefined){
				self.condition["page"]=this.pageInfo.pageNum;
				self.condition["rows"]=this.pageInfo.pageSize;
			}
			//发送请求,第一个参数http对象，第二个是url，第三个是参数，第四个是成功回调，第五个是请求失败回调
			customUtils.post(self,pageListUrl,self.condition,function(response,isSuccess){ 
				if(isSuccess==false){
				    dataList.pageInfo.pages=0;
				    customUtils.noData('无数据',0);
				    return;
				}
				dataList.pageInfo = response.body.pagination;
				customUtils.noData('无数据',dataList.pageInfo.pages);
				//页面初始化、搜索时，才需要执行分页控件
				if(eventSrc=='init' || eventSrc=='search'){
					customUtils.paging('#pagination',dataList.pageInfo.pages,customUtils.showPage,function(num){
						//当前页码pageNum与将要翻页的页码num不相等才执行，否则为同一页
						if(dataList.pageInfo.pageNum!=num){			    	
					    	dataList.pageInfo.pageNum=num;
							dataList.getList('paging');	
						}							    	
				    });
				}
            },function(response){
                console.log(response);
                dataList.pageInfo.pages=0;
			    customUtils.noData('无数据',0);
            });						
		},	
		//更新状态
		updateStatus:function(index){
			var record = this.pageInfo.list[index];
			var status = record.status==1?0:1;
			var param = {id:record.id,status:status};
			var self=this;
			customUtils.post(self,pageUrl + 'update',param,function(response,isSuccess){ 
				record.status=status;
				//根据需要刷新页面数据
				dataList.getList('init');
            },function(response){
                //console.log(response.body);
            });			
		},
		//初始化更新，更新对话框
		updateInit:function(index){
			//先显示窗口，才有加载效果
			this.addOrUpdatePanel("update");
			var record = this.pageInfo.list[index];
			this.selectedIdx=index;
			var url = pageUrl + 'id/'+record.id;
			var self=this;
			customUtils.get(self.$http,url,function(response,isSuccess){ 
				if(isSuccess==false){
				    return;
				}
				//回显表单数据
                var field = addOrUpdate.$data.field;
				$.each(response.body, function(key) {
					if(field[key]!==undefined && response.body[key]){
                        field[key] = response.body[key];
					}									 
				});
                addOrUpdate.$data.field.advType = response.body.advType
                addOrUpdate.typeChange();
				console.log(addOrUpdate.$data)
                if(response.body.areas){
                    addOrUpdate.$data.areaList = JSON.parse(response.body.areas);
                    var list = addOrUpdate.$data.areaList;
                    addOrUpdate.$data.areas = [];
                    for (var i = 0; i< list.length; i++) {
                        addOrUpdate.$data.areas.push(list[i].code);
                    }
                }
            },function(response){
                console.log(response);
            });
		},
        delAdv:function (id) {
	        var self = this;
            customUtils.post(self,pageUrl + "del",{id:id},function(response,isSuccess){
                customUtils.showTips(response.body,addOrUpdate.$data.err)
                dataList.getList('no');
            },function(response){
                //console.log(response.body);
            });
        },
		//打开添加对话框
		addOrUpdatePanel:function(flag){
            var obj1 = document.getElementById('topImg') ;
            obj1.outerHTML=obj1.outerHTML;
            var obj2 = document.getElementById('middleVideo') ;
            obj2.outerHTML=obj2.outerHTML;
	    	advInfo.clear(addOrUpdate.$data.err);
            advInfo.clear(addOrUpdate.$data.field);

            console.log(addOrUpdate.$data.field)
	    	if(flag != 'update'){
                addOrUpdate.$data.id="";
                addOrUpdate.$data.field.advType = '2';
                $(".t1").hide();
			}else{
                $(".t1").show();
            }
		    //清除表单数据，否则会有前一条修改数据的内容
            // $.each(addOrUpdate.$data, function(key) {
				// addOrUpdate[key]="";
            // });
			var tmpTitle =  flag=="add"?"添加":"修改";
            addOrUpdate.typeChange()
			addPanel = layer.open({
				type : 1,
				title :tmpTitle+"广告内容管理",
				area : [ '650px', '80%' ],
				shadeClose : false, // 点击遮罩关闭
				content : $('#addPanel')
			});
		}
	}
});
//绑定列表List---end---- 

//新增或更新---------begin-------
var addOrUpdate = new Vue({
	el:"#addPanel",
	data:{

        areas:[],
        areaList:[],
        provinces:[],
        province:"",
        city:"",
        area:"",
		//添加或修改表单字段
		field:{
            id:"",
            advCode:"",
            advName:"",
            advType:"3",
            maxAge:"",
            minAge:"",
            sex:"2",
			topImg:"",
			bottomImg:"",
			middleVideo:"",
            price:""
		},
		//错误信息
		err:{
            advCodeErr:"",
            advNameErr:"",
            maxAgeErr:"",
            minAgeErr:"",
            sexErr:"",
            advPathErr:"",
			topImgErr:"",
			bottomImgErr:"",
			middleVideoErr:"",
            advTypeErr:"",
            priceErr:""
		},
	showSuccess:true,//显示成功提示
	},
	//当需要在数据变化时执行异步或开销较大的操作时，这个方式是最有用的
    watch:{
    },
	methods:{		
	    changeTime:function(elem){
			addOrUpdate[elem.split('-')[0]] = $("#"+elem).val();               
		},
        typeChange:function () {
            var b = addOrUpdate.$data.field.advType;
            if(b ==6){
                $("#t1").hide();
                $("#t2").show();
                // $("#t_age").show();
                // $("#t_sex").show();
                // $("#tl").html("顶部图片：")
                // $("#ml").html("中部视频：")
                // $("#topImg").prop("multiple",false);
            }else{
                $("#t1").show();
                $("#t2").hide();
            }
            // if(b ==2){

            //     $("#t_age").hide();
            //     $("#t_sex").hide();
            //     $("#tl").html("前景图片：")
            //     $("#ml").html("背景音乐：")
            //     // $("#topImg").prop("multiple",true);
            // }
        },
		save:function(){

			//没有id的时候表示新增，否则为更新
			var actionUrl=this.field.id=="" ? 'save' :'update';
            //逻辑校验
            if(!advInfo.checkLogic(this.$data.field,this.$data.err,actionUrl)){
                return;
            }
			var self=this;
            var formDate = new FormData($("#addPanel")[0]);
            console.log(self.$data)
			customUtils.post(self,pageUrl + actionUrl,formDate,function(response,isSuccess){
			    customUtils.showTips(response.body,addOrUpdate.$data.err)
				dataList.getList('init');
				if(isSuccess && addPanel)layer.close(addPanel);
			},function(res){
                //console.log(response.body);
            });			
		},


        addArea:function () {
            var area = this.$data.area;
            var city = this.$data.city;
            var province = this.$data.province;
            if(area && area != "" && area != null){
                addOrUpdate.pushNoRepeat(this.$data.area);
            }else if(city && city != "" && city != null) {
                $.each(city.areas ,function(i){
                    addOrUpdate.pushNoRepeat(city.areas[i]);
                });
            }else if(province && province != "" && province != null){
                $.each(province.citys,function (i) {
                    $.each(province.citys[i].areas,function (j) {
                        addOrUpdate.pushNoRepeat(province.citys[i].areas[j]);
                    });
                })
            }
        },
        //避免重复添加
        pushNoRepeat:function(area){
            var fg = true;
            for (var i = 0; i< addOrUpdate.$data.areas.length; i++){
                if(addOrUpdate.$data.areas[i] == area.code){
                    fg = false;
                    break;
                }
            }
            if(fg){
                addOrUpdate.$data.areas.push(area.code);
                addOrUpdate.$data.areaList.push(area)
            }
        },
        cloce:function (code) {
            var index;
            for (var i = 0; i<addOrUpdate.$data.areaList.length; i++ ) {
                if(addOrUpdate.$data.areaList[i].code == code){
                    index = i;
                    break;
                }
            }
            addOrUpdate.$data.areaList.splice(index,1);
            addOrUpdate.$data.areas.splice($.inArray(code, addOrUpdate.$data.areas), 1);
        },
        setCitys:function () {
            advInfo.setCitys();
        },
        setAreas:function () {
            advInfo.setAreas();
        },
		//清除表单数据
		reset:function(){
            if(addPanel)layer.close(addPanel);
		}
	}
});
//新增或更新---------end-------
	
	
